<script>
import { uuid } from 'vue-uuid'
export default {
  name: 'LoginView',
  data () {
    return {
      sendMsg: '发送短信',
      resetSendMsg: '发送短信',
      sendBtnDisabled: false,
      resetSendBtn: false,
      inter: '',
      interTime: 60,
      isLogin: true,
      kaptchaSrc: '',
      resetDialog: false,
      resetFormData: {
        phone: '',
        uuid: '',
        code: '',
        password: '',
        confirmPassword: ''
      },
      resetFormRules: {
        phone: [
          { required: true, message: '手机号码不能为空' },
          { pattern: /^1\d{10}$/, message: '手机号码格式错误' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            validator: (rule, value, callback) => {
              if (value.length === 4) {
                callback()
              } else {
                callback(new Error('验证码长度必须为5位'))
              }
            }
          }
        ],
        password: [
          { required: true, message: '密码不能为空' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码' },
          {
            validator: (rule, value, callback) => {
              if (value === this.resetFormData.password) {
                callback()
              } else {
                callback(new Error('两次密码不一致'))
              }
            }
          }
        ]
      },
      registerFormData: {
        username: '',
        password: '',
        confirmPassword: '',
        code: '',
        uuid: '',
        phone: ''
      },
      registerFormRules: {
        username: [
          { required: true, message: '用户名不能为空' }
        ],
        password: [
          { required: true, message: '密码不能为空' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码' },
          {
            validator: (rule, value, callback) => {
              if (value === this.registerFormData.password) {
                callback()
              } else {
                callback(new Error('两次密码不一致'))
              }
            }
          }
        ],
        phone: [
          { required: true, message: '手机号码不能为空' },
          { pattern: /^1\d{10}$/, message: '手机号码格式错误' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            validator: (rule, value, callback) => {
              if (value.length === 4) {
                callback()
              } else {
                callback(new Error('验证码长度必须为5位'))
              }
            }
          }
        ]
      },
      loginFormData: {
        username: '',
        password: '',
        code: '',
        uuid: ''
      },
      loginFormRules: {
        username: [
          { required: true, message: '用户名不能为空' }
        ],
        password: [
          { required: true, message: '密码不能为空' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            validator: (rule, value, callback) => {
              if (value.length === 5) {
                callback()
              } else {
                callback(new Error('验证码长度必须为5位'))
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    getKaptcha () {
      this.loginFormData.uuid = uuid.v4()
      this.kaptchaSrc = process.env.VUE_APP_BASE_PATH + 'kaptcha.jpg?uuid=' + this.loginFormData.uuid
    },
    login () {
      this.$refs.loginFormRef.validate(valid => {
        if (valid) {
          this.$axios.post('login', this.loginFormData).then(data => {
            this.$message.success('登录成功')
            this.$cookies.set('token', data.TOKEN, '7d')
            this.$router.replace('/home')
          }).catch(() => {
            this.loginFormData.code = ''
            this.getKaptcha()
          })
        }
      })
    },
    register () {
      this.$refs.registerRef.validate(valid => {
        if (valid) {
          this.$axios.post('register', this.registerFormData).then(() => {
            this.$alert('注册成功，请登录！', { type: 'success' }).then(() => {
              this.isLogin = true
              this.registerFormData = { ...this.$options.data().registerFormData }
            })
          }).catch(() => {})
        }
      })
    },
    send () {
      if (!this.registerFormData.phone) {
        this.$message.error('请输入手机号！')
        return false
      }
      if (!(/^1\d{10}$/.test(this.registerFormData.phone))) {
        this.$message.error('请输入正确的手机号！')
        return false
      }
      this.$axios.get('register/send', { params: { phone: this.registerFormData.phone } }).then(data => {
        this.$message.success('发送成功！')
        this.registerFormData.uuid = data.uuid
        this.sendBtnDisabled = true
        this.interTime = 60
        this.inter = setInterval(() => {
          this.interTime--
          if (this.interTime === 0) {
            clearInterval(this.inter)
            this.sendBtnDisabled = false
            this.sendMsg = '发送短信'
          } else {
            this.sendMsg = (this.interTime < 10 ? '0' + this.interTime : this.interTime) + '秒后重试...'
          }
        }, 100)
      }).catch(() => {})
    },
    resetSend () {
      if (!this.resetFormData.phone) {
        this.$message.error('请输入手机号！')
        return false
      }
      if (!(/^1\d{10}$/.test(this.resetFormData.phone))) {
        this.$message.error('请输入正确的手机号！')
        return false
      }
      this.$axios.get('forget/send', { params: { phone: this.resetFormData.phone } }).then(data => {
        this.$message.success('发送成功！')
        this.resetFormData.uuid = data.uuid
        this.resetSendBtn = true
        this.interTime = 60
        this.inter = setInterval(() => {
          this.interTime--
          if (this.interTime === 0) {
            clearInterval(this.inter)
            this.resetSendBtn = false
            this.resetSendMsg = '发送短信'
          } else {
            this.resetSendMsg = (this.interTime < 10 ? '0' + this.interTime : this.interTime) + '秒后重试...'
          }
        }, 100)
      }).catch(() => {})
    },
    reset () {
      this.$refs.resetFormRef.validate(valid => {
        if (valid) {
          this.$axios.post('reset/password', this.resetFormData).then(() => {
            this.$message.success('重置密码成功！')
            this.resetDialog = false
            this.isLogin = true
          })
        }
      })
    }
  },
  created () {
    this.$nextTick(() => {
      this.getKaptcha()
    })
  },
  destroyed () {
    clearInterval(this.inter)
  }
}
</script>

<template>
<div class="content">
  <div class="form-group" v-if="isLogin" key="login">
    <h3>个人博客后台登录</h3>
    <el-form @keydown.enter.native="login" :model="loginFormData" :rules="loginFormRules" label-width="80px" ref="loginFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginFormData.username" clearable placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginFormData.password" clearable show-password placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="loginFormData.code" clearable placeholder="请输入验证码" :maxlength="5">
          <div slot="append" class="kaptcha-group">
            <img :src="kaptchaSrc" alt="验证码生成失败" title="点击更改验证码" @click="getKaptcha">
          </div>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="login">登录</el-button>
        <el-button type="text" @click="isLogin = false">点击注册</el-button>
        <el-button type="text" @click="resetDialog = true">忘记密码？</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="form-group" v-else key="register">
    <h3>注册账号</h3>
    <el-form @keydown.enter.native="register" :model="registerFormData" :rules="registerFormRules" label-width="80px" ref="registerRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerFormData.username" clearable placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="registerFormData.phone" clearable placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="registerFormData.code" :maxlength="4" clearable placeholder="请输入验证码" >
          <div class="phone-group" slot="append">
            <el-button :disabled="sendBtnDisabled" @click="send" type="text">{{ sendMsg }}</el-button>
          </div>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerFormData.password" clearable show-password placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="registerFormData.confirmPassword" clearable show-password placeholder="请再次输入密码"/>
      </el-form-item>
      <el-form-item>
        <el-button @click="register">注册</el-button>
        <el-button type="text" @click="isLogin = true">直接登录</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-dialog :visible.sync="resetDialog" title="重置密码" width="550px">
    <div class="form-group">
      <el-form @keydown.enter.native="reset" :model="resetFormData" :rules="resetFormRules" ref="resetFormRef" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="resetFormData.phone" placeholder="请输入手机号" clearable/>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="resetFormData.code" :maxlength="4" clearable placeholder="请输入验证码" >
            <div class="phone-group" slot="append">
              <el-button :disabled="resetSendBtn" @click="resetSend" type="text">{{ resetSendMsg }}</el-button>
            </div>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="resetFormData.password" clearable show-password placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetFormData.confirmPassword" clearable show-password placeholder="请再次输入密码"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</div>
</template>
<style>
.el-input-group__append{
  padding: 0;
}
</style>
<style scoped lang="scss">
.content{
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("@/assets/login-bg.jpg") no-repeat center/cover;
  .form-group{
    width: 500px;
    background-color: rgba(255,255,255,.4);
    padding: 15px;
    border-radius: 20px;
    &>h3{
      text-align: center;
    }
    .kaptcha-group{
      height: 40px;
      width: 160px;
      img{
        display: block;
        height: 100%;
        width: 100%;
      }
    }
    .phone-group{
      width: 160px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
